package com.leaf.lowcode.controller;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.leaf.lowcode.domain.JsonData;
import com.leaf.lowcode.entity.video_bussiness.SearchRequest;
import com.leaf.lowcode.sdk.video_bussiness.ArtemisPostTest_Resource;
import com.leaf.lowcode.utils.RegularInstance;
import com.tencent.welink.iot.SubDeviceDTO;
import com.tencent.welink.iot.WelinkHttp;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/hik")
@PropertySource({"classpath:resource.properties"})
public class HikController {
    @Value("${ArtemisConfig.host}")
    private String host;

    @Value("${ArtemisConfig.appKey}")
    private String appKey;

    @Value("${ArtemisConfig.appSecret}")
    private String appSecret;

    @PostMapping(value="getRes")
    @ResponseBody
    public void getRes(@RequestBody JSONObject jsonObject) {
        List paramslist = (ArrayList)jsonObject.getJSONObject("params").get("events");
        if(paramslist!=null){
            //子设备列表
            List<SubDeviceDTO> subDeviceDTOList = RegularInstance.subDeviceDTOList;
            if(subDeviceDTOList!=null) {
                for (SubDeviceDTO dto : subDeviceDTOList) {
                    String pid = dto.getPid();
                    String sn = dto.getSn();
                    String din = dto.getDin();
                    if ("1701001494".equalsIgnoreCase(pid)) {
                        System.out.println("捕捉到设备1701001494-----------------------");
                        for(int i=0;i<paramslist.size();i++){
                            LinkedHashMap map = (LinkedHashMap)paramslist.get(i);
                            int eventType = Integer.parseInt(map.get("eventType").toString());
                            if(eventType==192517){
                                String happenTime = map.get("happenTime").toString();
                                LinkedHashMap mapData = (LinkedHashMap)map.get("data");
                                List thermometrylist = (ArrayList)mapData.get("thermometry");
                                if(thermometrylist!=null){
                                    JSONObject standardData = new JSONObject();
                                    standardData.put("reportTs",System.currentTimeMillis());
                                    JSONObject profile = new JSONObject();
                                    profile.put("modelId","200446");
                                    profile.put("appType","security_monitoring");
                                    profile.put("poiCode","w0301007");
                                    standardData.put("profile",profile);
                                    WelinkHttp wh = new WelinkHttp(RegularInstance.registerData1, RegularInstance.loginData);
                                    for(int j=0;j<thermometrylist.size();j++){
                                        LinkedHashMap mapThe = (LinkedHashMap)thermometrylist.get(i);
//                                        System.out.println(mapThe.get("ruleTemperature").toString());
//                                        System.out.println(mapThe.get("curTemperature").toString());
//                                        System.out.println(mapThe.get("alarmLevel").toString());
//                                        System.out.println(mapThe.get("point").toString());
//                                        System.out.println(((LinkedHashMap)mapThe.get("targetAttrs")).get("cameraIndexCode").toString());
                                        SearchRequest sr = new SearchRequest();
                                        sr.setPageNo(1);
                                        sr.setPageSize(1);
                                        sr.setCameraIndexCodes(((LinkedHashMap)mapThe.get("targetAttrs")).get("cameraIndexCode").toString());
                                        String search = ArtemisPostTest_Resource.search(sr);
//                                        JSONObject searchData = JSONObject.parseObject(search);
                                        System.out.println("search=="+search);
                                        JSONObject events = new JSONObject();
                                        JSONObject event = new JSONObject();
                                        event.put("ruleTemperature", mapThe.get("ruleTemperature"));
                                        event.put("curTemperature", mapThe.get("curTemperature"));
                                        event.put("alarmLevel", mapThe.get("alarmLevel"));
                                        event.put("eventType", 0);
                                        event.put("eventTs", System.currentTimeMillis());
                                        event.put("describe", "");
                                        event.put("point", mapThe.get("point"));
//                                        event.put("caremaName", searchData.get("carema"));
                                        event.put("cameraIndexCode", ((LinkedHashMap)mapThe.get("targetAttrs")).get("cameraIndexCode"));

                                        // event.put("search", search);
                                        events.put("fire", event);
                                        standardData.put("events", events);
                                        standardData.put("properties", new JSONObject());
                                        try {
                                            String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);
                                            System.out.println("发送设备运行时事件数据==" + devRunEvent);
                                            System.out.println("--------------------------------开始传输设备运行时事件数据");
                                            wh.sendMessage(RegularInstance.loginData.load(), 80000, Long.parseLong(din), devRunEvent, true);
                                        } catch (Exception e) {
                                            System.out.println("设备运行时事件数据传输出现异常");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        }
    }


    @PostMapping(value="getCountGroup")
    @ResponseBody
    public JsonData getCountGroup(@RequestBody JSONObject jsonObject) {
        Object regionId = jsonObject.get("regionId");
        Object isCascade = jsonObject.get("isCascade");
        Object groupType = jsonObject.get("groupType");
        Object statType = jsonObject.get("statType");
        Object pageNo = jsonObject.get("pageNo");
        Object pageSize = jsonObject.get("pageSize");

        if (null == groupType || null == pageNo || null == pageSize) {
            return new JsonData(-1, "缺少参数groupType\\pageNo\\pageSize，请填写正确参数");
        }else {
            /**
             * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
             */
            ArtemisConfig.host = host; // artemis网关服务器ip端口
            ArtemisConfig.appKey = appKey; // 秘钥appkey
            ArtemisConfig.appSecret = appSecret;// 秘钥appSecret


            final String ARTEMIS_PATH = "/artemis";
            //STEP3：设置接口的URI地址
            final String previewURLsApi = ARTEMIS_PATH + "/api/cfas/v2/countGroup/groups/page";
            Map<String, String> path = new HashMap <String, String>(2) {
                {
                    put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
                }
            };
            //STEP4：设置参数提交方式
            String contentType = "application/json";
            //STEP5：组装请求参数
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("groupType", Integer.parseInt(groupType.toString()));
            jsonBody.put("pageNo", Integer.parseInt(pageNo.toString()));
            jsonBody.put("pageSize", Integer.parseInt(pageSize.toString()));
            if (null != regionId){
                jsonBody.put("regionId", regionId.toString());
            }
            if (null != isCascade){
                jsonBody.put("isCascade", Integer.parseInt(isCascade.toString()));
            }
            if (null != statType){
                jsonBody.put("statType", Integer.parseInt(statType.toString()));
            }
            String body = jsonBody.toJSONString();

            //STEP6：调用接口
            System.out.println("数据请求地址:https://" + path.get("https://"));
            String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null,
                    contentType , null);
            System.out.println("数据请求响应：" + result);
            return new JsonData(1, result);
        }
    }

    @PostMapping(value="getRealTime")
    @ResponseBody
    public JsonData getRealTime(@RequestBody JSONObject jsonObject) {
        Object ids = jsonObject.get("ids");
        if (ids == null) {
            return new JsonData(-1, "缺少参数ids，请填写正确参数");
        }else {
            List<String> params = Arrays.asList(ids.toString().split(","));
            System.out.println(params.toString());

            ArtemisConfig.host = host; // artemis网关服务器ip端口
            ArtemisConfig.appKey = appKey; // 秘钥appkey
            ArtemisConfig.appSecret = appSecret;// 秘钥appSecret
            //System.out.println(ids.toString());
            final String ARTEMIS_PATH = "/artemis";
            //STEP3：设置接口的URI地址
            final String previewURLsApi = ARTEMIS_PATH + "/api/cfas/v3/passenger/realTime";
            Map<String, String> path = new HashMap<String, String>(2) {
                {
                    put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
                }
            };
            //STEP4：设置参数提交方式
            String contentType = "application/json";
            //STEP5：组装请求参数
            JSONObject jsonBody = new JSONObject();
            String body = jsonBody.toJSONString();
            jsonBody.put("req", params);

            //STEP6：调用接口
            String result = ArtemisHttpUtil.doPostStringArtemis(path, params.toString(), null, null,
                    contentType, null);
            return new JsonData(1, result);
        }
    }



    @PostMapping(value="getEventLogs")
    @ResponseBody
    public JsonData getEventLogs(@RequestBody JSONObject jsonObject) {
        Object regionId = jsonObject.get("regionId");
        Object isCascade = jsonObject.get("isCascade");
        Object groupType = jsonObject.get("groupType");
        Object statType = jsonObject.get("statType");
        Object pageNo = jsonObject.get("pageNo");
        Object pageSize = jsonObject.get("pageSize");

        if (null == groupType || null == pageNo || null == pageSize) {
            return new JsonData(-1, "缺少参数groupType\\pageNo\\pageSize，请填写正确参数");
        }else {
            /**
             * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
             */
            ArtemisConfig.host = host; // artemis网关服务器ip端口
            ArtemisConfig.appKey = appKey; // 秘钥appkey
            ArtemisConfig.appSecret = appSecret;// 秘钥appSecret


            final String ARTEMIS_PATH = "/artemis";
            //STEP3：设置接口的URI地址
            final String previewURLsApi = ARTEMIS_PATH + "/api/scpms/v2/eventLogs/searches";
            Map<String, String> path = new HashMap <String, String>(2) {
                {
                    put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
                }
            };
            //STEP4：设置参数提交方式
            String contentType = "application/json";
            //STEP5：组装请求参数
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("groupType", Integer.parseInt(groupType.toString()));
            jsonBody.put("pageNo", Integer.parseInt(pageNo.toString()));
            jsonBody.put("pageSize", Integer.parseInt(pageSize.toString()));
            if (null != regionId){
                jsonBody.put("regionId", regionId.toString());
            }
            if (null != isCascade){
                jsonBody.put("isCascade", Integer.parseInt(isCascade.toString()));
            }
            if (null != statType){
                jsonBody.put("statType", Integer.parseInt(statType.toString()));
            }
            String body = jsonBody.toJSONString();

            //STEP6：调用接口
            String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null,
                    contentType , null);
            return new JsonData(1, result);
        }
    }
}
